//
//  WBNewFeatureView.swift
//  SinaMicroblog
//
//  Created by 原鹏飞 on 2017/4/8.
//  Copyright © 2017年 YuanPengFei. All rights reserved.
//

import UIKit

class WBNewFeatureView: UIView {
    
    /// 懒加载属性: scrollView
    lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView(frame: self.bounds)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true
        scrollView.bounces = false
        scrollView.delegate = self
        
        return scrollView
    }()
    
    
    /// 懒加载属性: pageControl (分页控制器)
    lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.pageIndicatorTintColor = UIColor.black
        pageControl.currentPageIndicatorTintColor = globalColor
        pageControl.currentPage = 0
        pageControl.numberOfPages = 4
        
        return pageControl
    }()
    
    
    /// 初始化的时候就设置UI
    override init(frame: CGRect) {
        super.init(frame: screenBounds)
        self.setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


// MARK: - 设置UI
extension WBNewFeatureView {
    func setupUI() {
        //1. 添加子视图
        addSubview(scrollView)
        addSubview(pageControl)
        
        //2. 自动布局
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-100)
        }
        
        //3. 添加新特性页的图片
        for i in 1...4 {
            let imageView = UIImageView(imageName: "new_feature_\(i)")
            imageView.frame = screenBounds.offsetBy(dx: CGFloat(i - 1) * screenWidth, dy: 0)
            scrollView.addSubview(imageView)
        }
        
        //4. 设置scrollView的contentSize
        scrollView.contentSize = CGSize(width: screenWidth * 5, height: screenHeight)
    }
}


extension WBNewFeatureView: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offSetX = scrollView.contentOffset.x
        
        //计算当前的页数
        let page = Int(offSetX / screenWidth + 0.5) //四舍五入算法
        pageControl.currentPage = page
        
        //隐藏pageControl
        pageControl.isHidden = offSetX > (screenWidth * 3.3)
        
        //移除newFeature
        if (offSetX >= screenWidth * 4) {
            self.removeFromSuperview()
        }
    }
}
